package com.movisol.messengerprofileservice.asynctasks;

import java.util.List;

import android.os.AsyncTask;
import android.widget.Toast;

import com.movisol.messengerprofileservice.controllers.ProfileController;
import com.movisol.messengerprofileservice.data.Friends;
import com.movisol.messengerprofileservice.exceptions.ProfileServiceWebFault;
import com.movisol.messengerprofileservice.helpers.MessengerProfileHelper;
import com.movisol.messengerprofileservice.interfaces.errorcodes.SaveUserProfileErrorCodes;
import com.movisol.messengerprofileservice.interfaces.errorcodes.UpdateFriendsErrorCodes;
import com.movisol.tools.HelperUtils;

public class AsyncFriendListLoad extends AsyncTask<Void, Void, String> {

	private ProfileController	pc	= ProfileController.getInstance();

	@Override
	protected String doInBackground(Void... params) {
		String sku = HelperUtils.getConfigParam("SKU", pc.getContext());
		String version = HelperUtils.getApplicationVersion(pc.getContext());
		String languageId = HelperUtils.getDeviceCountry();
		String userId = pc.getUserProfile().getUserId();
		String signature = MessengerProfileHelper.generateSignature(userId
				+ HelperUtils.getConfigParam("ProfileSecretPhrase", pc.getContext()));
		return pc.getUserFriends(sku, version, languageId, userId, signature);
	}

	@Override
	protected void onPostExecute(String result) {
		// We need to fire the event in here due to the UI restrictions about
		// modifying components in other threads
		super.onPostExecute(result);
		if (result != null)
		{
			List<Object> list = MessengerProfileHelper.parseXMLfriendsToObject(result);
			if (list.get(0) != null)
			{
				pc.setFriends((Friends) list.get(0));
				pc.fireFriendsDataLoadedEvent(null);
			}
			if (list.get(1) != null)
			{
				String error = UpdateFriendsErrorCodes.getErrorByCode(((ProfileServiceWebFault) list.get(1))
						.getIntegerErrorCode());
				pc.fireFriendsDataLoadedEvent(error);
				HelperUtils.LogE(getClass(), error);
				HelperUtils.showToastMessage(pc.getContext(), error, Toast.LENGTH_SHORT);
			}
		} else
		{
			HelperUtils.LogE(getClass(), null);
			pc.fireFriendsDataLoadedEvent(SaveUserProfileErrorCodes
					.getErrorByCode(SaveUserProfileErrorCodes.INTERNAL_ERROR));
		}
	}
}
